package absolute_zero.com.urbox.transmition;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Environment;
import android.util.Log;
import android.widget.ProgressBar;
/**
 * Transmition Server Multi-Threading for the Android P2P application
 * 
 * @author Charles C. Francis
 * @version 0.01a:
 * Initial build
 * @version 0.02a:
 * Added class variables to track time
 *
 */
public class ServerThread extends Thread
{
	private Socket _socket = null;
	/**
	 * Stores the Start Time of the Thread
	 * @since 0.02a
	 */
	protected long startTime = 0;
	/**
	 * Stores the Current Time of the Thread
	 * @since 0.02a
	 */
	protected long elapsed = 0;
	/**
	 * Stores the Final Time of the Thread
	 * @since 0.02a
	 */
	protected long end = 0;
	private int bytesRead;
	private int fileSize = 0;
	private ProgressBar progress;
	private InputStream is;
	/**
	 * create the processing thread
	 * @param socket the socket connection to the server
	 * @param progress 
	 */
	public ServerThread(Socket socket, ProgressBar progressbar)
	{
		_socket = socket;
		try {
			_socket.setReuseAddress(true);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.progress = progressbar;
	}
	/**
	 * processes and receives the file
	 */
	@Override
	public void run()
	{
			Log.d("Server Threaed instantiated", "ST started");
		BufferedReader reader = null;
		String fileName = "";
		try {
			is = _socket.getInputStream();
			//read the name and size from the input
			reader = new BufferedReader(new InputStreamReader(is), 32);
			//Returns string like Name: file_nameLength: file length.  Parse out theese two values
			String name = reader.readLine();
			String size = reader.readLine();
			
			 fileName = name;
			 Log.d("Name String Post Parsage", fileName);
			 		fileSize = Integer.valueOf(size);
			//Make sure this info was transmitted properly
			Log.d("Size", Integer.toString(fileSize));
		} catch (IOException e) {
			Log.d("IOException", e.toString());
		}
		//this is the start download time.  not used now, but can be used later
		this.startTime = System.currentTimeMillis();
		double bytesread = 0;
    	progress.setIndeterminate(false);
		progress.setMax(101);
        //progress.setProgress(5); 
		byte[] transArray = new byte[fileSize];
		try {
			//open streams
			FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/urbox/" + fileName);
			BufferedOutputStream bufStr = new BufferedOutputStream(fos);
			while(is.available() != 0){
				bytesread = (int)bytesread + is.read(transArray, (int)bytesread, transArray.length - (int)bytesread);
				progress.setProgress((int)(bytesread/fileSize));
				Log.d("Bytes read", Integer.toString((int)bytesread));
			}
			progress.setProgress(101);
			//bufStr.flush();
			//download ending time
			bufStr.write(transArray);
			bufStr.flush();
			fos.flush();
			this.end = System.currentTimeMillis();
			fos.close();
			bufStr.close();
			_socket.close();
		} catch (IOException e) {
			Log.d("IOException", e.toString());
		}
		/*
		 * NOTE: to use the download time, total time is end - start, elapsed time is currentTime - start
		 */
		
	}
	/**
	 * @return Start Time of the thread
	 * @since 0.02a
	 */
	public long getStartTime()
	{
		return startTime;
	}
	
	public int get_bytes_read(){
		return bytesRead;
	}
	/**
	 * @return Elapsed time of the thread
	 * @since 0.02a
	 */
	public long getElapsedTime()
	{
		return elapsed - startTime;
	}
	/**
	 * 
	 * @return Current time of the thread
	 * @since 0.02a
	 */
	public long getCurrentTime()
	{
		return elapsed;
	}
	/**
	 * 
	 * @return Ending time of the Thread
	 * @since 0.02a
	 */
	public long getEndTime()
	{
		return end;
	}

}
